package com.kolaxy.netty.chat;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.ArrayList;
import java.util.List;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    public static List<Channel> channels = new ArrayList<Channel>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        Channel channel = ctx.channel();
        channels.add(channel);
        System.out.println(msg);

        for (Channel channel1 : channels) {
            channel1.writeAndFlush(Unpooled.copiedBuffer("hahahaha", CharsetUtil.UTF_8));
//            if (channel1 != channel) {
//            }
        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel inChannel = ctx.channel();
        System.out.println("[SERVER:]" + inChannel.remoteAddress().toString().substring(1) + "offline");
        channels.remove(inChannel);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel inChannel = ctx.channel();
        System.out.println("[SERVER:]" + inChannel.remoteAddress().toString().substring(1) + "online");
    }


}
